<?php
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2010 osCommerce

  Released under the GNU General  License
*/


// start the timer for the page parse time log
  define('PAGE_PARSE_START_TIME', microtime());

// set the level of error reporting
  error_reporting(E_ALL & ~E_NOTICE);

// check support for register_globals
  if (function_exists('ini_get') && (ini_get('register_globals') == false) && (PHP_VERSION < 4.3) ) {
    exit('Server Requirement Error: register_globals is disabled in your PHP configuration. This can be enabled in your php.ini configuration file or in the .htaccess file in your catalog directory. Please use PHP 4.3+ if register_globals cannot be enabled on the server.');
  }

// load server configuration parameters
  if (file_exists('includes/local/configure.php')) { // for developers
    include('includes/local/configure.php');
  } else {
    include('includes/configure.php');
  }

  if (strlen(DB_SERVER) < 1) {
    if (is_dir('install')) {
      header('Location: install/index.php');
    }
  }

// define the project version --- obsolete, now retrieved with tep_get_version()
  define('PROJECT_VERSION', 'osCommerce Online Merchant v2.3');

// some code to solve compatibility issues
  require(DIR_WS_FUNCTIONS . 'compatibility.php');

// set the type of request (secure or not)
  $request_type = (getenv('HTTPS') == 'on') ? 'SSL' : 'NONSSL';

// set php_self in the local scope
  $PHP_SELF = (((strlen(ini_get('cgi.fix_pathinfo')) > 0) && ((bool)ini_get('cgi.fix_pathinfo') == false)) || !isset($HTTP_SERVER_VARS['SCRIPT_NAME'])) ? basename($HTTP_SERVER_VARS['PHP_SELF']) : basename($HTTP_SERVER_VARS['SCRIPT_NAME']);

  if ($request_type == 'NONSSL') {
    define('DIR_WS_CATALOG', DIR_WS_HTTP_CATALOG);
  } else {
    define('DIR_WS_CATALOG', DIR_WS_HTTPS_CATALOG);
  }

// include the list of project filenames
  require(DIR_WS_INCLUDES . 'filenames.php');

// include the list of project database tables
  require(DIR_WS_INCLUDES . 'database_tables.php');

// include the database functions
  require(DIR_WS_FUNCTIONS . 'database.php');

// make a connection to the database... now
  tep_db_connect() or die('Unable to connect to database server!');

// set the application parameters
  $configuration_query = tep_db_query('select configuration_key as cfgKey, configuration_value as cfgValue from ' . TABLE_CONFIGURATION);
  while ($configuration = tep_db_fetch_array($configuration_query)) {
    define($configuration['cfgKey'], $configuration['cfgValue']);
  }


// set the HTTP GET parameters manually if search_engine_friendly_urls is enabled
  if (SEARCH_ENGINE_FRIENDLY_URLS == 'true') {
    if (strlen(getenv('PATH_INFO')) > 1) {
      $GET_array = array();
      $PHP_SELF = str_replace(getenv('PATH_INFO'), '', $PHP_SELF);
      $vars = explode('/', substr(getenv('PATH_INFO'), 1));
      do_magic_quotes_gpc($vars);
      for ($i=0, $n=sizeof($vars); $i<$n; $i++) {
        if (strpos($vars[$i], '[]')) {
          $GET_array[substr($vars[$i], 0, -2)][] = $vars[$i+1];
        } else {
          $HTTP_GET_VARS[$vars[$i]] = $vars[$i+1];
        }
        $i++;
      }

      if (sizeof($GET_array) > 0) {
        while (list($key, $value) = each($GET_array)) {
          $HTTP_GET_VARS[$key] = $value;
        }
      }
    }
  }

// define general functions used application-wide
  require(DIR_WS_FUNCTIONS . 'general.php');
  require(DIR_WS_FUNCTIONS . 'html_output.php');

// set the cookie domain
  $cookie_domain = (($request_type == 'NONSSL') ? HTTP_COOKIE_DOMAIN : HTTPS_COOKIE_DOMAIN);
  $cookie_path = (($request_type == 'NONSSL') ? HTTP_COOKIE_PATH : HTTPS_COOKIE_PATH);

// include cache functions if enabled
  if (USE_CACHE == 'true') include(DIR_WS_FUNCTIONS . 'cache.php');

// include shopping cart class
  require(DIR_WS_CLASSES . 'shopping_cart.php');

// include navigation history class
  require(DIR_WS_CLASSES . 'navigation_history.php');

// define how the session functions will be used
  require(DIR_WS_FUNCTIONS . 'sessions.php');

// set the session name and save path
  tep_session_name('osCsid');
  tep_session_save_path(SESSION_WRITE_DIRECTORY);

// set the session cookie parameters
   if (function_exists('session_set_cookie_params')) {
    session_set_cookie_params(0, $cookie_path, $cookie_domain);
  } elseif (function_exists('ini_set')) {
    ini_set('session.cookie_lifetime', '0');
    ini_set('session.cookie_path', $cookie_path);
    ini_set('session.cookie_domain', $cookie_domain);
  }

  @ini_set('session.use_only_cookies', (SESSION_FORCE_COOKIE_USE == 'True') ? 1 : 0);

// set the session ID if it exists
   if (isset($HTTP_POST_VARS[tep_session_name()])) {
     tep_session_id($HTTP_POST_VARS[tep_session_name()]);
   } elseif ( ($request_type == 'SSL') && isset($HTTP_GET_VARS[tep_session_name()]) ) {
     tep_session_id($HTTP_GET_VARS[tep_session_name()]);
   }

// start the session
  $session_started = false;
  if (SESSION_FORCE_COOKIE_USE == 'True') {
    tep_setcookie('cookie_test', 'please_accept_for_session', time()+60*60*24*30, $cookie_path, $cookie_domain);

    if (isset($HTTP_COOKIE_VARS['cookie_test'])) {
      tep_session_start();
      $session_started = true;
    }
  } elseif (SESSION_BLOCK_SPIDERS == 'True') {
    $user_agent = strtolower(getenv('HTTP_USER_AGENT'));
    $spider_flag = false;

    if (tep_not_null($user_agent)) {
      $spiders = file(DIR_WS_INCLUDES . 'spiders.txt');

      for ($i=0, $n=sizeof($spiders); $i<$n; $i++) {
        if (tep_not_null($spiders[$i])) {
          if (is_integer(strpos($user_agent, trim($spiders[$i])))) {
            $spider_flag = true;
            break;
          }
        }
      }
    }

    if ($spider_flag == false) {
      tep_session_start();
      $session_started = true;
    }
  } else {
    tep_session_start();
    $session_started = true;
  }

  if ( ($session_started == true) && (PHP_VERSION >= 4.3) && function_exists('ini_get') && (ini_get('register_globals') == false) ) {
    extract($_SESSION, EXTR_OVERWRITE+EXTR_REFS);
  }

// initialize a session token
  if (!tep_session_is_registered('sessiontoken')) {
    $sessiontoken = md5(tep_rand() . tep_rand() . tep_rand() . tep_rand());
    tep_session_register('sessiontoken');
  }

// set SID once, even if empty
  $SID = (defined('SID') ? SID : '');

// verify the ssl_session_id if the feature is enabled
  if ( ($request_type == 'SSL') && (SESSION_CHECK_SSL_SESSION_ID == 'True') && (ENABLE_SSL == true) && ($session_started == true) ) {
    $ssl_session_id = getenv('SSL_SESSION_ID');
    if (!tep_session_is_registered('SSL_SESSION_ID')) {
      $SESSION_SSL_ID = $ssl_session_id;
      tep_session_register('SESSION_SSL_ID');
    }

    if ($SESSION_SSL_ID != $ssl_session_id) {
      tep_session_destroy();
      tep_redirect(tep_href_link(FILENAME_SSL_CHECK));
    }
  }

// verify the browser user agent if the feature is enabled
  if (SESSION_CHECK_USER_AGENT == 'True') {
    $http_user_agent = getenv('HTTP_USER_AGENT');
    if (!tep_session_is_registered('SESSION_USER_AGENT')) {
      $SESSION_USER_AGENT = $http_user_agent;
      tep_session_register('SESSION_USER_AGENT');
    }

    if ($SESSION_USER_AGENT != $http_user_agent) {
      tep_session_destroy();
      tep_redirect(tep_href_link(FILENAME_LOGIN));
    }
  }

// verify the IP address if the feature is enabled
  if (SESSION_CHECK_IP_ADDRESS == 'True') {
    $ip_address = tep_get_ip_address();
    if (!tep_session_is_registered('SESSION_IP_ADDRESS')) {
      $SESSION_IP_ADDRESS = $ip_address;
      tep_session_register('SESSION_IP_ADDRESS');
    }

    if ($SESSION_IP_ADDRESS != $ip_address) {
      tep_session_destroy();
      tep_redirect(tep_href_link(FILENAME_LOGIN));
    }
  }

// create the shopping cart
  if (!tep_session_is_registered('cart') || !is_object($cart)) {
    tep_session_register('cart');
    $cart = new shoppingCart;
  }

// include currencies class and create an instance
  require(DIR_WS_CLASSES . 'currencies.php');
  $currencies = new currencies();

// include the mail classes
  require(DIR_WS_CLASSES . 'mime.php');
  require(DIR_WS_CLASSES . 'email.php');

// set the language
  if (!tep_session_is_registered('language') || isset($HTTP_GET_VARS['language'])) {
    if (!tep_session_is_registered('language')) {
      tep_session_register('language');
      tep_session_register('languages_id');
    }

    include(DIR_WS_CLASSES . 'language.php');
    $lng = new language();

    if (isset($HTTP_GET_VARS['language']) && tep_not_null($HTTP_GET_VARS['language'])) {
      $lng->set_language($HTTP_GET_VARS['language']);
    } else {
      $lng->get_browser_language();
    }

    $language = $lng->language['directory'];
    $languages_id = $lng->language['id'];
  }

// include the language translations  
  require(DIR_WS_LANGUAGES . $language . '.php');
  require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_DEFAULT);

// currency
  if (!tep_session_is_registered('currency') || isset($HTTP_GET_VARS['currency']) || ( (USE_DEFAULT_LANGUAGE_CURRENCY == 'true') && (LANGUAGE_CURRENCY != $currency) ) ) {
    if (!tep_session_is_registered('currency')) tep_session_register('currency');

    if (isset($HTTP_GET_VARS['currency']) && $currencies->is_set($HTTP_GET_VARS['currency'])) {
      $currency = $HTTP_GET_VARS['currency'];
    } else {
      $currency = ((USE_DEFAULT_LANGUAGE_CURRENCY == 'true') && $currencies->is_set(LANGUAGE_CURRENCY)) ? LANGUAGE_CURRENCY : DEFAULT_CURRENCY;
    }
  }

// navigation history
  if (!tep_session_is_registered('navigation') || !is_object($navigation)) {
    tep_session_register('navigation');
    $navigation = new navigationHistory;
  }
  $navigation->add_current_page();

// action recorder
  include('includes/classes/action_recorder.php');

// Shopping cart actions
  if (isset($HTTP_GET_VARS['action'])) {
// redirect the customer to a friendly cookie-must-be-enabled page if cookies are disabled
    if ($session_started == false) {
      tep_redirect(tep_href_link(FILENAME_COOKIE_USAGE));
    }

    if (DISPLAY_CART == 'true') {
      $goto =  FILENAME_SHOPPING_CART;
      $parameters = array('action', 'cPath', 'products_id', 'pid');
    } else {
      $goto = basename($PHP_SELF);
      if ($HTTP_GET_VARS['action'] == 'buy_now') {
        $parameters = array('action', 'pid', 'products_id');
      } else {
        $parameters = array('action', 'pid');
      }
    }    
  }

 switch ($HTTP_GET_VARS['action']) {
      // performed by the 'buy now' button in product listings and review page
      case 'buy_now' :        if (isset($HTTP_GET_VARS['products_id'])) {
                                if (tep_has_product_attributes($HTTP_GET_VARS['products_id'])) {
                                  tep_redirect(tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $HTTP_GET_VARS['products_id']));
                                } else {
                                  $cart->add_cart($HTTP_GET_VARS['products_id'], $cart->get_quantity($HTTP_GET_VARS['products_id'])+1);
                                }
                              }							
                              tep_redirect(tep_href_link(FILENAME_SHOPPING_CART, tep_get_all_get_params($parameters)));
                              break;
    }
    

// include validation functions (right now only email address)
  require(DIR_WS_FUNCTIONS . 'validations.php');

// split-page-results
  require(DIR_WS_CLASSES . 'split_page_results.php');

// infobox
  require(DIR_WS_CLASSES . 'boxes.php');


// auto expire special products
  require(DIR_WS_FUNCTIONS . 'specials.php');
  tep_expire_specials();

  require(DIR_WS_CLASSES . 'osc_template.php');
  $oscTemplate = new oscTemplate();

// calculate category path
  if (isset($HTTP_GET_VARS['cPath'])) {
    $cPath = $HTTP_GET_VARS['cPath'];
  } elseif (isset($HTTP_GET_VARS['products_id']) && !isset($HTTP_GET_VARS['manufacturers_id'])) {
    $cPath = tep_get_product_path($HTTP_GET_VARS['products_id']);
  } else {
    $cPath = '';
  }

  if (tep_not_null($cPath)) {
    $cPath_array = tep_parse_category_path($cPath);
    $cPath = implode('_', $cPath_array);
    $current_category_id = $cPath_array[(sizeof($cPath_array)-1)];
  } else {
    $current_category_id = 0;
  }

// include the breadcrumb class and start the breadcrumb trail
  require(DIR_WS_CLASSES . 'breadcrumb.php');
  $breadcrumb = new breadcrumb;

  $breadcrumb->add(HEADER_TITLE_TOP, HTTP_SERVER);
  $breadcrumb->add(HEADER_TITLE_CATALOG, tep_href_link(FILENAME_DEFAULT));

// add category names or the manufacturer name to the breadcrumb trail
  if (isset($cPath_array)) {
    for ($i=0, $n=sizeof($cPath_array); $i<$n; $i++) {
      $categories_query = tep_db_query("select categories_name from " . TABLE_CATEGORIES_DESCRIPTION . " where categories_id = '" . (int)$cPath_array[$i] . "' and language_id = '" . (int)$languages_id . "'");
      if (tep_db_num_rows($categories_query) > 0) {
        $categories = tep_db_fetch_array($categories_query);
        $breadcrumb->add($categories['categories_name'], tep_href_link(FILENAME_DEFAULT, 'cPath=' . implode('_', array_slice($cPath_array, 0, ($i+1)))));
      } else {
        break;
      }
    }
  } elseif (isset($HTTP_GET_VARS['manufacturers_id'])) {
    $manufacturers_query = tep_db_query("select manufacturers_name from " . TABLE_MANUFACTURERS . " where manufacturers_id = '" . (int)$HTTP_GET_VARS['manufacturers_id'] . "'");
    if (tep_db_num_rows($manufacturers_query)) {
      $manufacturers = tep_db_fetch_array($manufacturers_query);
      $breadcrumb->add($manufacturers['manufacturers_name'], tep_href_link(FILENAME_DEFAULT, 'manufacturers_id=' . $HTTP_GET_VARS['manufacturers_id']));
    }
  }

// add the products model to the breadcrumb trail
  if (isset($HTTP_GET_VARS['products_id'])) {
    $model_query = tep_db_query("select products_model from " . TABLE_PRODUCTS . " where products_id = '" . (int)$HTTP_GET_VARS['products_id'] . "'");
    if (tep_db_num_rows($model_query)) {
      $model = tep_db_fetch_array($model_query);
      $breadcrumb->add($model['products_model'], tep_href_link(FILENAME_PRODUCT_INFO, 'cPath=' . $cPath . '&products_id=' . $HTTP_GET_VARS['products_id']));
    }
  }

// initialize the message stack for output messages
  require(DIR_WS_CLASSES . 'message_stack.php');
  $messageStack = new messageStack;
  
  $error = false;

  if ( (isset($HTTP_GET_VARS['keywords']) && empty($HTTP_GET_VARS['keywords'])) &&
       (isset($HTTP_GET_VARS['dfrom']) && (empty($HTTP_GET_VARS['dfrom']) || ($HTTP_GET_VARS['dfrom'] == DOB_FORMAT_STRING))) &&
       (isset($HTTP_GET_VARS['dto']) && (empty($HTTP_GET_VARS['dto']) || ($HTTP_GET_VARS['dto'] == DOB_FORMAT_STRING))) &&
       (isset($HTTP_GET_VARS['pfrom']) && !is_numeric($HTTP_GET_VARS['pfrom'])) &&
       (isset($HTTP_GET_VARS['pto']) && !is_numeric($HTTP_GET_VARS['pto'])) ) {
    $error = true;

    $messageStack->add_session('search', ERROR_AT_LEAST_ONE_INPUT);
  } else {
    $dfrom = '';
    $dto = '';
    $pfrom = '';
    $pto = '';
    $keywords = '';

    if (isset($HTTP_GET_VARS['dfrom'])) {
      $dfrom = (($HTTP_GET_VARS['dfrom'] == DOB_FORMAT_STRING) ? '' : $HTTP_GET_VARS['dfrom']);
    }

    if (isset($HTTP_GET_VARS['dto'])) {
      $dto = (($HTTP_GET_VARS['dto'] == DOB_FORMAT_STRING) ? '' : $HTTP_GET_VARS['dto']);
    }

    if (isset($HTTP_GET_VARS['pfrom'])) {
      $pfrom = $HTTP_GET_VARS['pfrom'];
    }

    if (isset($HTTP_GET_VARS['pto'])) {
      $pto = $HTTP_GET_VARS['pto'];
    }

    if (isset($HTTP_GET_VARS['keywords'])) {
      $keywords = tep_db_prepare_input($HTTP_GET_VARS['keywords']);
    }

    $date_check_error = false;
    if (tep_not_null($dfrom)) {
      if (!tep_checkdate($dfrom, DOB_FORMAT_STRING, $dfrom_array)) {
        $error = true;
        $date_check_error = true;

        $messageStack->add_session('search', ERROR_INVALID_FROM_DATE);
      }
    }

    if (tep_not_null($dto)) {
      if (!tep_checkdate($dto, DOB_FORMAT_STRING, $dto_array)) {
        $error = true;
        $date_check_error = true;

        $messageStack->add_session('search', ERROR_INVALID_TO_DATE);
      }
    }

    if (($date_check_error == false) && tep_not_null($dfrom) && tep_not_null($dto)) {
      if (mktime(0, 0, 0, $dfrom_array[1], $dfrom_array[2], $dfrom_array[0]) > mktime(0, 0, 0, $dto_array[1], $dto_array[2], $dto_array[0])) {
        $error = true;

        $messageStack->add_session('search', ERROR_TO_DATE_LESS_THAN_FROM_DATE);
      }
    }

    $price_check_error = false;
    if (tep_not_null($pfrom)) {
      if (!settype($pfrom, 'double')) {
        $error = true;
        $price_check_error = true;

        $messageStack->add_session('search', ERROR_PRICE_FROM_MUST_BE_NUM);
      }
    }

    if (tep_not_null($pto)) {
      if (!settype($pto, 'double')) {
        $error = true;
        $price_check_error = true;

        $messageStack->add_session('search', ERROR_PRICE_TO_MUST_BE_NUM);
      }
    }

    if (($price_check_error == false) && is_float($pfrom) && is_float($pto)) {
      if ($pfrom >= $pto) {
        $error = true;

        $messageStack->add_session('search', ERROR_PRICE_TO_LESS_THAN_PRICE_FROM);
      }
    }

    if (tep_not_null($keywords)) {
      if (!tep_parse_search_string($keywords, $search_keywords)) {
        $error = true;

        $messageStack->add_session('search', ERROR_INVALID_KEYWORDS);
      }
    }
  }

  if (empty($dfrom) && empty($dto) && empty($pfrom) && empty($pto) && empty($keywords)) {
    $error = true;

    $messageStack->add_session('search', ERROR_AT_LEAST_ONE_INPUT);
  }

  if ($error == true) {
    //tep_redirect(tep_href_link(FILENAME_ADVANCED_SEARCH, tep_get_all_get_params(), 'NONSSL', true, false));
  }

  $breadcrumb->add(NAVBAR_TITLE_1, tep_href_link(FILENAME_ADVANCED_SEARCH));
  $breadcrumb->add(NAVBAR_TITLE_2, tep_href_link(FILENAME_ADVANCED_SEARCH_RESULT, tep_get_all_get_params(), 'NONSSL', true, false));

?>




<?php
// create column list
  $define_list = array('PRODUCT_LIST_MODEL' => PRODUCT_LIST_MODEL,
                       'PRODUCT_LIST_NAME' => PRODUCT_LIST_NAME,
                       'PRODUCT_LIST_MANUFACTURER' => PRODUCT_LIST_MANUFACTURER,
                       'PRODUCT_LIST_PRICE' => PRODUCT_LIST_PRICE,
                       'PRODUCT_LIST_QUANTITY' => PRODUCT_LIST_QUANTITY,
                       'PRODUCT_LIST_WEIGHT' => PRODUCT_LIST_WEIGHT,
                       'PRODUCT_LIST_IMAGE' => PRODUCT_LIST_IMAGE,
                       'PRODUCT_LIST_BUY_NOW' => PRODUCT_LIST_BUY_NOW);

  asort($define_list);

  $column_list = array();
  reset($define_list);
  while (list($key, $value) = each($define_list)) {
    if ($value > 0) $column_list[] = $key;
  }

  $select_column_list = '';

  for ($i=0, $n=sizeof($column_list); $i<$n; $i++) {
    switch ($column_list[$i]) {
      case 'PRODUCT_LIST_MODEL':
        $select_column_list .= 'p.products_model, ';
        break;
      case 'PRODUCT_LIST_MANUFACTURER':
        $select_column_list .= 'm.manufacturers_name, ';
        break;
      case 'PRODUCT_LIST_QUANTITY':
        $select_column_list .= 'p.products_quantity, ';
        break;
      case 'PRODUCT_LIST_IMAGE':
        $select_column_list .= 'p.products_image, ';
        break;
      case 'PRODUCT_LIST_WEIGHT':
        $select_column_list .= 'p.products_weight, ';
        break;
    }
  }

  $select_str = "select distinct " . $select_column_list . " m.manufacturers_id, p.products_id, pd.products_name, p.products_price, p.products_tax_class_id, IF(s.status, s.specials_new_products_price, NULL) as specials_new_products_price, IF(s.status, s.specials_new_products_price, p.products_price) as final_price ";

  if ( (DISPLAY_PRICE_WITH_TAX == 'true') && (tep_not_null($pfrom) || tep_not_null($pto)) ) {
    $select_str .= ", SUM(tr.tax_rate) as tax_rate ";
  }

  $from_str = "from " . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m using(manufacturers_id) left join " . TABLE_SPECIALS . " s on p.products_id = s.products_id";

  if ( (DISPLAY_PRICE_WITH_TAX == 'true') && (tep_not_null($pfrom) || tep_not_null($pto)) ) {
    if (!tep_session_is_registered('customer_country_id')) {
      $customer_country_id = STORE_COUNTRY;
      $customer_zone_id = STORE_ZONE;
    }
    $from_str .= " left join " . TABLE_TAX_RATES . " tr on p.products_tax_class_id = tr.tax_class_id left join " . TABLE_ZONES_TO_GEO_ZONES . " gz on tr.tax_zone_id = gz.geo_zone_id and (gz.zone_country_id is null or gz.zone_country_id = '0' or gz.zone_country_id = '" . (int)$customer_country_id . "') and (gz.zone_id is null or gz.zone_id = '0' or gz.zone_id = '" . (int)$customer_zone_id . "')";
  }

  $from_str .= ", " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";

  $where_str = " where p.products_status = '1' and p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id ";

  //tim theo category
  if (isset($HTTP_GET_VARS['categories_id']) && tep_not_null($HTTP_GET_VARS['categories_id'])) {
    if (isset($HTTP_GET_VARS['inc_subcat']) && ($HTTP_GET_VARS['inc_subcat'] == '1')) {
      $subcategories_array = array();
      tep_get_subcategories($subcategories_array, $HTTP_GET_VARS['categories_id']);

      $where_str .= " and p2c.products_id = p.products_id and p2c.products_id = pd.products_id and (p2c.categories_id = '" . (int)$HTTP_GET_VARS['categories_id'] . "'";

      for ($i=0, $n=sizeof($subcategories_array); $i<$n; $i++ ) {
        $where_str .= " or p2c.categories_id = '" . (int)$subcategories_array[$i] . "'";
      }

      $where_str .= ")";
    } else {
      $where_str .= " and p2c.products_id = p.products_id and p2c.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and p2c.categories_id = '" . (int)$HTTP_GET_VARS['categories_id'] . "'";
    }
  }

  $cPath = $HTTP_GET_VARS['cPath']; $wManu = '';
  //tim theo nha san xuat
  if (isset($HTTP_GET_VARS['manufacturers_id']) && tep_not_null($HTTP_GET_VARS['manufacturers_id'])) {
    $manu = explode('_', $HTTP_GET_VARS['manufacturers_id']);
    $wManu = implode(',', $manu);
    $where_str .= " and m.manufacturers_id in (" . $wManu . ")";
  }
 
  //tim theo gia
  $price_to = $price_from = 0; 
  
  if (isset($HTTP_GET_VARS['price_to']) && tep_not_null($HTTP_GET_VARS['price_to'])) {      
      $price_to = $HTTP_GET_VARS['price_to'];
  }
  else  $price_to='';
         
  if (isset($HTTP_GET_VARS['price_from']) && tep_not_null($HTTP_GET_VARS['price_from'])) {
      $price_from = $HTTP_GET_VARS['price_from'];
  }
  else  $price_from ='';
  
  $currencies_array = $currencies->currencies;
  $cCurrentcy = $currencies_array[$currency];
  
  if ($price_to) $price_to = $price_to/$cCurrentcy['value'];
  
  if ($price_from) $price_from = $price_from/$cCurrentcy['value'];

  $precision = $cCurrentcy ['decimal_places']; //add by donghp

  $where_price ='';
  
  if($price_from && $price_to){
      if($price_from <= $price_to){
          $where_str .= " and p.products_price >= '" . $price_from . "' and p.products_price <= '" . $price_to . "'";
$where_price.=" and p.products_price >= '" . $price_from . "' and p.products_price <= '" . $price_to . "'";		  
      }else{
          $where_str .= " and p.products_price >= '" . $price_to . "' and p.products_price <= '" . $price_from . "'";
$where_price.= " and p.products_price >= '" . $price_to . "' and p.products_price <= '" . $price_from . "'";		  
      }      
  }elseif($price_from && !$price_to){
      $where_str .= " and p.products_price >= '" . $price_from . "'";
	  
	  $where_price.=" and p.products_price >= '" . $price_from . "'";
	  
  }elseif(!$price_from && $price_to){
      $where_str .= " and p.products_price <= '" . $price_to . "'";
	  
	  $where_price.=" and p.products_price >= '" . $price_from . "'";
  }    
  /*
  //---------------------------------------------------------------
  if (isset($search_keywords) && (sizeof($search_keywords) > 0)) {
    $where_str .= " and (";
    for ($i=0, $n=sizeof($search_keywords); $i<$n; $i++ ) {
      switch ($search_keywords[$i]) {
        case '(':
        case ')':
        case 'and':
        case 'or':
          $where_str .= " " . $search_keywords[$i] . " ";
          break;
        default:
          $keyword = tep_db_prepare_input($search_keywords[$i]);
          $where_str .= "(pd.products_name like '%" . tep_db_input($keyword) . "%' or p.products_model like '%" . tep_db_input($keyword) . "%' or m.manufacturers_name like '%" . tep_db_input($keyword) . "%'";
          if (isset($HTTP_GET_VARS['search_in_description']) && ($HTTP_GET_VARS['search_in_description'] == '1')) $where_str .= " or pd.products_description like '%" . tep_db_input($keyword) . "%'";
          $where_str .= ')';
          break;
      }
    }
    $where_str .= " )";
  }

  if (tep_not_null($dfrom)) {
    $where_str .= " and p.products_date_added >= '" . tep_date_raw($dfrom) . "'";
  }

  if (tep_not_null($dto)) {
    $where_str .= " and p.products_date_added <= '" . tep_date_raw($dto) . "'";
  }

  if (tep_not_null($pfrom)) {
    if ($currencies->is_set($currency)) {
      $rate = $currencies->get_value($currency);

      $pfrom = $pfrom / $rate;
    }
  }

  if (tep_not_null($pto)) {
    if (isset($rate)) {
      $pto = $pto / $rate;
    }
  }

  if (DISPLAY_PRICE_WITH_TAX == 'true') {
    if ($pfrom > 0) $where_str .= " and (IF(s.status, s.specials_new_products_price, p.products_price) * if(gz.geo_zone_id is null, 1, 1 + (tr.tax_rate / 100) ) >= " . (double)$pfrom . ")";
    if ($pto > 0) $where_str .= " and (IF(s.status, s.specials_new_products_price, p.products_price) * if(gz.geo_zone_id is null, 1, 1 + (tr.tax_rate / 100) ) <= " . (double)$pto . ")";
  } else {
    if ($pfrom > 0) $where_str .= " and (IF(s.status, s.specials_new_products_price, p.products_price) >= " . (double)$pfrom . ")";
    if ($pto > 0) $where_str .= " and (IF(s.status, s.specials_new_products_price, p.products_price) <= " . (double)$pto . ")";
  }

  if ( (DISPLAY_PRICE_WITH_TAX == 'true') && (tep_not_null($pfrom) || tep_not_null($pto)) ) {
    $where_str .= " group by p.products_id, tr.tax_priority";
  }

  if ( (!isset($HTTP_GET_VARS['sort'])) || (!pregu_match('/^[1-8][ad]$/', $HTTP_GET_VARS['sort'])) || (substr($HTTP_GET_VARS['sort'], 0, 1) > sizeof($column_list)) ) {
    for ($i=0, $n=sizeof($column_list); $i<$n; $i++) {
      if ($column_list[$i] == 'PRODUCT_LIST_NAME') {
        $HTTP_GET_VARS['sort'] = $i+1 . 'a';
        $order_str = " order by pd.products_name";
        break;
      }
    }
  } else {
    $sort_col = substr($HTTP_GET_VARS['sort'], 0 , 1);
    $sort_order = substr($HTTP_GET_VARS['sort'], 1);

    switch ($column_list[$sort_col-1]) {
      case 'PRODUCT_LIST_MODEL':
        $order_str = " order by p.products_model " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name";
        break;
      case 'PRODUCT_LIST_NAME':
        $order_str = " order by pd.products_name " . ($sort_order == 'd' ? 'desc' : '');
        break;
      case 'PRODUCT_LIST_MANUFACTURER':
        $order_str = " order by m.manufacturers_name " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name";
        break;
      case 'PRODUCT_LIST_QUANTITY':
        $order_str = " order by p.products_quantity " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name";
        break;
      case 'PRODUCT_LIST_IMAGE':
        $order_str = " order by pd.products_name";
        break;
      case 'PRODUCT_LIST_WEIGHT':
        $order_str = " order by p.products_weight " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name";
        break;
      case 'PRODUCT_LIST_PRICE':
        $order_str = " order by final_price " . ($sort_order == 'd' ? 'desc' : '') . ", pd.products_name";
        break;
    }
  }

  $listing_sql = $select_str . $from_str . $where_str . $order_str;
  */

	$i = 0;
    $menu = array();
	$manufactures = array();

     if (!count($manufactures)) {
                            $menu = get_menu();
                        }
						
	$cPath_array_new = $cPath_array;
        
	$id = $cPath_array[count($cPath_array) - 1];
		               
	$categories_string='';		$case = 0;	$show_price=0;
		     
//--------By DongHP Show Price Fillter----------
if (isset($HTTP_GET_VARS['case'])) $case = 0+$HTTP_GET_VARS['case']; //-----Case = 2 ko hien thi lai gia

if (isset($HTTP_GET_VARS['case'])) $show_price = 0+$HTTP_GET_VARS['show_price']; //-----Case = 2 ko hien thi lai gia

$ok = empty($price_from) && empty($price_to);

$print_menu_price="";

/*$categories_string='<span style="color:#E17009; font-weight: bold;">Price </span>' .
                                '<div id="any_price" class="anyPrice" style="margin:5px 0px 0px 10px; ">
<a href="#" onclick="javascript:any_price_click();"> &laquo;Any price</a></div>' .
								*/
// $categories_string='<div class="price" style="margin-left:0px;">';
                      
//-------Hien thi thang gia de tim kiem-------------
						
 if (SHOW_COUNTS == 'true') {
                            $categories_string .= '<div> <a href="javascript:void(0);" onclick="choose_price(0,' . show_currency(40).','.$precision.');">Under ' . $cCurrentcy['symbol_left'] . show_currency(40) . $cCurrentcy['symbol_right'] . '</a>&nbsp;' . cya_count_products_in_price($id, 0, show_currency(40)) . '</div>' .
                                    '<div> <a href="javascript:void(0);" onclick="choose_price(' . show_currency(40) . ',' . show_currency(100) .','.$precision.');">' . $cCurrentcy['symbol_left'] . 
									show_currency(40) . $cCurrentcy['symbol_right'] . ' to ' . $cCurrentcy['symbol_left'] . show_currency(100) . $cCurrentcy['symbol_right'] . '</a>&nbsp;
                    ' . cya_count_products_in_price($id, show_currency(40), show_currency(100)) . '</div>' .
                                    '<div> <a href="javascript:void(0);" onclick="choose_price(' . show_currency(100) . ',' . show_currency(200) .','.$precision.');">' . $cCurrentcy['symbol_left'] . show_currency(100) . $cCurrentcy['symbol_right'] . ' to ' . $cCurrentcy['symbol_left'] . show_currency(200) . $cCurrentcy['symbol_right'] . '</a>&nbsp;
                    ' . cya_count_products_in_price($id, show_currency(100), show_currency(200)) . '</div>' .
                                    '<div> <a href="javascript:void(0);" onclick="choose_price(' . show_currency(200) . ',' . show_currency(400) .','.$precision.');">' . $cCurrentcy['symbol_left'] . show_currency(200) . $cCurrentcy['symbol_right'] . ' to ' . $cCurrentcy['symbol_left'] . show_currency(400) . $cCurrentcy['symbol_right'] . '</a>&nbsp;
                    ' . cya_count_products_in_price($id, show_currency(200), show_currency(400)) . '</div>' .
                                    '<div> <a href="javascript:void(0);" onclick="choose_price(' . show_currency(400) . ',0,'.$precision.');">Over ' . $cCurrentcy['symbol_left'] . show_currency(400) . $cCurrentcy['symbol_right'] . '</a>&nbsp;
                    ' . cya_count_products_in_price($id, show_currency(400), 9999999999) . '</div>';
                        } else {
                            $categories_string .= '<div> <a href="javascript:void(0);" onclick="choose_price(0,' . show_currency(40).','.$precision.');">Under ' . $cCurrentcy['symbol_left'] . show_currency(40) . $cCurrentcy['symbol_right'] . '</a></div>' .
                                    '<div> <a href="javascript:void(0);" onclick="choose_price(' . show_currency(40) . ',' . show_currency(100) .','.$precision.');">' . $cCurrentcy['symbol_left'] . show_currency(40) . $cCurrentcy['symbol_right'] . ' to ' . $cCurrentcy['symbol_left'] . show_currency(100) . $cCurrentcy['symbol_right'] . '</a></div>' .
                                    '<div> <a href="javascript:void(0);" onclick="choose_price(' . show_currency(100) . ',' . show_currency(200) .','.$precision.');">' . $cCurrentcy['symbol_left'] . show_currency(100) . $cCurrentcy['symbol_right'] . ' to ' . $cCurrentcy['symbol_left'] . show_currency(200) . $cCurrentcy['symbol_right'] . '</a></div>' .
                                    '<div> <a href="javascript:void(0);" onclick="choose_price(' . show_currency(200) . ',' . show_currency(400) .','.$precision.');>' . $cCurrentcy['symbol_left'] . show_currency(200) . $cCurrentcy['symbol_right'] . ' to ' . $cCurrentcy['symbol_left'] . show_currency(400) . $cCurrentcy['symbol_right'] . '</a></div>' .
                                    '<div> <a href="javascript:void(0);
                    " onclick="choose_price(' . show_currency(400) .',0,'.$precision.')
                    ">Over ' . $cCurrentcy['symbol_left'] . show_currency(400) . $cCurrentcy['symbol_right'] . '</a></div>';
                        }

                        //ket thuc div price
                  /*      $categories_string.='</div>';

                        $categories_string .=
                                '<div style="margin-top: 5px;margin-left: 0px;"><div>' . $cCurrentcy['symbol_left'] . '<input class="input1" id="ip_price_from" value="'.$price_from.'" type="text" size="2"/>' . $cCurrentcy['symbol_right'] . ' to </div><div>' . $cCurrentcy['symbol_left'] . '<input class="input2" id="ip_price_to" value="'.$price_to.'" type="text" size="2">' . $cCurrentcy['symbol_right'] . '
                                <span  style="margin-right:0px;
                    position: relative;
                    "><a href="javascript:void(0)" onclick="search_price()" ><img src="images/go_icon.gif" width="13px" height="13px" border="0" style="position: relative;
                    top: 4px;
                    " /></a></span></div>
                            </div>' .
                                '<input type="hidden" name="cya" id="cya" value="" />' .
                                '<input type="hidden" name="price_to" id="price_to" value="" />' .
                                '<input type="hidden" name="price_from" id="price_from" value="" />' .
                                '<input type="hidden" name="filter_sort" id="filter_sort" value="2a"/>' .
                                '<input type="hidden" name="filter_page" id="filter_page" value="1" />';

                        //ket thuc div div_all_price */
     $categories_string.='[:|:]';

//--------------------------------BRAND Filter DIV by donghp---------------------------
 $categories_string.= '<span style="color:#E17009; font-weight: bold;">Brand</span>';
 $categories_string.= '<div id="clear" style="float:left; margin: 0px 0px 0px 10px; width: 115px;">
 <div onclick="javascript:clear_brand();">Clear</div></div>';
 $categories_string.= '<div style="margin-left:0px; margin-top:5px; color: #2E6E9E;" id="show_manu">';
       
    if (is_array($menu) && count($menu)) {
                            foreach ($menu as $value) {								
							 
							 $c_d = cya_count_products_in_manu($id, $value['manufacturers_id']);
							 							 
							 if ($c_d !='' or !empty($c_d))
							   {
								  $checked='';
								  $id_checked = ''.$value['manufacturers_id'];
								  								 
								  if (is_array($manu))
								  if  (count($manu)>0 && in_array( $id_checked ,$manu)) 
								  	{ $checked="checked=checked"; }
								   
                                $categories_string.= '<div id="mamu_' . $value['manufacturers_id'] . '"> <input name="manu_ids[]" onclick="javascript:filter_product2();" id="manu_ids[]" type="checkbox" value="' . $value['manufacturers_id'] . '" '.$checked.'/>' . $value['manufacturers_name'] . '&nbsp;' . $c_d . '</div>';
                                  $i++;	
							      }
                                  							   
	//echo $value['manufacturers_id'].'= ' .cya_count_products_in_manu($id, $value['manufacturers_id']) ."<br>";
                            }
							
                        }
	
	                        //ket thuc div show_manu
                        $categories_string.='</div>';
                        $categories_string.= '<div id="seemore" class="see_more"  style="margin-bottom:2px; margin-left: 20px;"><a href="#"> &raquo; See more</a></div>';

											
	echo trim($categories_string);		
//---------------------------------------------------------------------------------------------	
function show_currency($value_input) {
        
		global $currency, $currencies;

        $currencies_array = $currencies->currencies;
        
		$cCurrentcy = $currencies_array[$currency]; //$cCurrentcy['decimal_places']
        $rate_filter = $cCurrentcy['rate_filter'];
        
		$value_out = $value_input * $rate_filter;
		
		$value_out = number_format($value_out,(int) $cCurrentcy['decimal_places']);

        return $value_out;//edit by donghp
}
	
function get_menu() {
        global $cPath_array;
     	//---------By DongHP -----------------------------
	   //---------Email : donghp712@gmail.com ------------	
		$manufactures=array();
       /*
        $sql = "select distinct m.manufacturers_id";
        $sql .= " from " . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m using(manufacturers_id)";
        $sql .= " , " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";
        $sql .= " where p.products_status = '1' and p.products_id = pd.products_id and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and c.categories_id=" . $id;
		*/
		 $id = $cPath_array[count($cPath_array) - 1];
       
	   //--brands are sorted by total products viewed ----
       $sql = "select distinct m.manufacturers_id,SUM( pd.products_viewed ) AS total_views ";
      
	   $sql .= " from " . TABLE_PRODUCTS . " p left join " . TABLE_MANUFACTURERS . " m using(manufacturers_id)";
       $sql .= " , " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_CATEGORIES . " c, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c";
       $sql .= " where p.products_status = '1' and p.products_id = pd.products_id and p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and c.categories_id=" . $id; 
	   $sql .=" GROUP BY p.manufacturers_id ORDER BY total_views DESC";
	   
        $exit_m = array();
        $m_id_query = mysql_query($sql);
        while ($manu_id = tep_db_fetch_array($m_id_query)) {
            $exit_m[] = $manu_id['manufacturers_id'];
            $m_query = mysql_query("select manufacturers_name,manufacturers_id from " . TABLE_MANUFACTURERS . " where manufacturers_id = " . $manu_id['manufacturers_id'] . " order by manufacturers_id ASC");
            while ($manufacture = tep_db_fetch_array($m_query)) {
                $manufactures[] = $manufacture;
            }
        }
		return $manufactures;	
}

function cya_count_products_in_price($category_id, $price_from, $price_to) {
        global $currencies, $currency,$manu,$wManu; //add by donghp - querry with price range
						
        $products_count = 0;

        $currencies_array = $currencies->currencies;
        $cCurrentcy = $currencies_array[$currency];
        $price_to = $price_to / $cCurrentcy['value'];
        $price_from = $price_from / $cCurrentcy['value'];
        
		if ($price_to ===9999999999)
		  {
			  $q= "select count(*) as total from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where p.products_id = p2c.products_id and p.products_status = '1' and p2c.categories_id = '" . (int) $category_id . "' and p.products_price >= '" . $price_from . "'";			  
		  }
		 else
		  {
			  $q="select count(*) as total from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where p.products_id = p2c.products_id and p.products_status = '1' and p2c.categories_id = '" . (int) $category_id . "' and p.products_price >= " . $price_from . " and p.products_price <= " . $price_to . "";
		  }
		 
		 if ($wManu!=='')
    	$q .= " and p.manufacturers_id in (" . $wManu . ")";
		
		//echo $q."<br>";
		  
        $products_query = tep_db_query($q);      
		
        $products = tep_db_fetch_array($products_query);
        $products_count += $products['total'];
        if ($products_count) {
            return '(' . $products_count . ')';
        }
        return '';
    }
	
function cya_count_products_in_manu($category_id, $manu_id) {
		
		global $where_price,$wManu; //add by donghp - querry with price range
		
		if ($wManu!=='')
    	$where_str .= " and p.manufacturers_id in (" . $wManu . ")";
	
		$q = "select count(*) as total from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where p.products_id = p2c.products_id and p.products_status = '1' and p2c.categories_id = '" . (int) $category_id . "' and p.manufacturers_id ='" . $manu_id . "'".$where_price;
		
        $products_count = 0;
		
        $products_query = tep_db_query($q);
        
		//echo "sql = $q <br>";
		
        $products = tep_db_fetch_array($products_query);
        $products_count = $products['total'];
		
		//echo "c = $products_count <br>";
		
        if ($products_count>0) {
            return '(' . $products_count . ')';
        }
		else
        return '';
    }
?>
